# Paper: Is it still the economy? Economic voting in polarized politics
# County-level model
# Replication: Figure S3 (Supplementary Material)
remove(list = ls())

library(conflicted)
library(tidyverse)
conflict_prefer("filter","dplyr")
library(ggplot2)
library(dplyr)
library(here)
conflict_prefer("here", "here")
library(systemfit)

load(here("Final_Paper", "R&R", "CountyLevel.RData"))



summary(ols_model <- lm(inc_share ~ unemp_rate*elitepolar_house + 
                          log(defl_pcincome) +
                          share_black + share_hisp + share_asian + 
                          share_young + share_elder + log(tot_pop) + 
                          log1p(share_college) + log1p(share_manuf) +
                          as.factor(rural_urban) + state_partiesdiff + 
                          lag_incshare + state + rep_inc + incumbent_cand, 
                        data = model_data))
(ols_inc <- cbind(Estimate = coef(ols_model), confint(ols_model, level = 0.95)))

length(ols_inc[,1])
ols_inc[2,]
ols_inc[74,]

olsunem <- ols_inc[2,] #change in unemployment rate
olsint <- ols_inc[74,] #interaction

variables <- c("Unemp.", "Unemp.*Polarization")
ols_results <- rbind(olsunem, olsint)
glimpse(ols_results)

ols_data <- data.frame(variables, ols_results) %>% 
  mutate(model = "OLS") %>% 
  mutate(equation = "Vote Share")
glimpse(ols_data)

coef(summary(ols_model))[2,2]
coef(summary(ols_model))[74,2]    
se_unemp <- coef(summary(ols_model))[2,2]
se_int <- coef(summary(ols_model))[74,2]
se_ols <- rbind(se_unemp, se_int)
ols_data <- cbind(ols_data, se_ols)
glimpse(ols_data)

vcov(ols_model)[2, 2]
sqrt(vcov(ols_model)[2, 2])
sqrt(vcov(ols_model)[74, 74])
cov_unemp <- vcov(ols_model)[2, 74]


ols_data <- ols_data %>% 
  mutate(covb = ifelse(variables == "Unemp.*Polarization", cov_unemp, 0))

ols_data06 <- ols_data %>% 
  mutate(Estimate = ifelse(variables == "Unemp.*Polarization",
                           0.6*Estimate, Estimate)) %>% 
  mutate(polarization = 0.6) 
ols_data08 <- ols_data %>% 
  mutate(Estimate = ifelse(variables == "Unemp.*Polarization",
                           0.85*Estimate, Estimate)) %>% 
  mutate(polarization = 0.85)

ols_data <- ols_data %>% 
  mutate(polarization = 1)

ols_data <- rbind(ols_data, ols_data06, ols_data08)
glimpse(ols_data)

ols_data <- ols_data %>% 
  mutate(varb = ifelse(variables == "Unemp.",
                       se_ols^2, polarization^2*se_ols^2)) 

ols_data2 <- ols_data %>% 
  mutate(variables = ifelse(variables == "Unemp.", "Unemp.*Polarization", variables)) %>% 
  group_by(equation, polarization, variables) %>% 
  summarise(Estimate = sum(Estimate),
            vars = sum(varb),
            covb = sum(covb)) %>% 
  ungroup()
glimpse(ols_data2)

# standard error of marginal effects
ols_data2 <- ols_data2 %>% 
  mutate(se = sqrt(vars + 2*polarization*covb))
ols_data2 <- ols_data2 %>% 
  select(equation:Estimate, se)

ols_data <- ols_data %>% 
  filter(polarization == 1) %>% 
  filter(variables == "Unemp.") %>% 
  mutate(polarization = 0)
ols_data <- ols_data %>% 
  select(equation, variables, polarization, Estimate, se = se_ols)

ols_data <- rbind(ols_data, ols_data2)
glimpse(ols_data)

ols_data <- ols_data %>% 
  mutate(icii = Estimate+(1.96*se)) %>% 
  mutate(ici = Estimate-(1.96*se))

sd(model_data$unemp_rate)
mean(model_data$unemp_rate)

ols_data <- ols_data %>% 
  mutate(mean_unemp = mean(model_data$unemp_rate)) %>% 
  mutate(sd_uenmp = sd(model_data$unemp_rate)) %>% 
  mutate(estimate_mean_unemp = sd_uenmp*Estimate) %>% 
  mutate(icii_new = estimate_mean_unemp+(1.96*se)) %>% 
  mutate(ici_new = estimate_mean_unemp-(1.96*se))
glimpse(ols_data)


ols_data <- ols_data %>%
  mutate(polarization = as.factor(polarization)) %>%  
  mutate(polarization = factor(polarization, 
                               levels = c("0",
                                          "0.6",
                                          "0.85",
                                          "1"))) %>% 
  mutate(equation = "Incumbent Party")

fig_ols <- ols_data %>% 
  filter(!(polarization == 1)) %>%
  filter(!(polarization == 0)) %>%
  #filter(variables == "Unemp.Rate" | variables == "Unemp.Rate*Polarization") %>% 
  ggplot(aes(color = polarization, shape = polarization, fill = polarization)) +
  geom_hline(yintercept = 0, colour = "gray57", lty = 2, size = .75) +
  geom_pointrange(aes(x = equation, y = estimate_mean_unemp, ymin = ici_new,
                      ymax = icii_new),
                  lwd = .65, position = position_dodge(width = .5)) + 
  theme_bw() + 
  ylab("Change in Vote Share") + xlab(NULL) + #ylim(-0.1, 0.05) +
  scale_color_manual(name = "Polarization:",
                     values = c("#009999", "#990000"), 
                     labels = c("0.60", "0.85")) +
  scale_shape_manual(name = "Polarization:",
                     values = c(24, 25), 
                     labels = c("0.60", "0.85")) +
  scale_fill_manual(name = "Polarization:",
                    values = c("#009999", "#990000"), 
                    labels = c("0.60", "0.85")) +
  #ggtitle("(c) log(Opposition/Abstention)") +
  theme(axis.text.x = element_blank(),
        axis.text.y = element_text(size = 11),
        axis.title.y = element_text(size = 13),
        legend.text = element_text(size = 13),
        legend.title = element_text(size = 14),
        legend.position = "bottom",
        legend.direction = "horizontal",
        title = element_text(size = 13)) +
  ggtitle("(a) Unemployment Rate")
fig_ols

################################################################################

summary(ols_model <- lm(inc_share ~ change_unemprate*elitepolar_house + 
                          log(defl_pcincome) +
                          share_black + share_hisp + share_asian + 
                          share_young + share_elder + log(tot_pop) + 
                          log1p(share_college) + log1p(share_manuf) +
                          as.factor(rural_urban) + state_partiesdiff + 
                          lag_incshare + state + rep_inc + incumbent_cand, 
                        data = model_data))
(ols_inc <- cbind(Estimate = coef(ols_model), confint(ols_model, level = 0.95)))

length(ols_inc[,1])
ols_inc[2,]
ols_inc[74,]

olsunem <- ols_inc[2,] #change in unemployment rate
olsint <- ols_inc[74,] #interaction

variables <- c("Unemp.", "Unemp.*Polarization")
ols_results <- rbind(olsunem, olsint)
glimpse(ols_results)

ols_data <- data.frame(variables, ols_results) %>% 
  mutate(model = "OLS") %>% 
  mutate(equation = "Vote Share")
glimpse(ols_data)

coef(summary(ols_model))[2,2]
coef(summary(ols_model))[74,2]    
se_unemp <- coef(summary(ols_model))[2,2]
se_int <- coef(summary(ols_model))[74,2]
se_ols <- rbind(se_unemp, se_int)
ols_data <- cbind(ols_data, se_ols)
glimpse(ols_data)

vcov(ols_model)[2, 2]
sqrt(vcov(ols_model)[2, 2])
sqrt(vcov(ols_model)[74, 74])
cov_unemp <- vcov(ols_model)[2, 74]


ols_data <- ols_data %>% 
  mutate(covb = ifelse(variables == "Unemp.*Polarization", cov_unemp, 0))

ols_data06 <- ols_data %>% 
  mutate(Estimate = ifelse(variables == "Unemp.*Polarization",
                           0.6*Estimate, Estimate)) %>% 
  mutate(polarization = 0.6) 
ols_data08 <- ols_data %>% 
  mutate(Estimate = ifelse(variables == "Unemp.*Polarization",
                           0.85*Estimate, Estimate)) %>% 
  mutate(polarization = 0.85)

ols_data <- ols_data %>% 
  mutate(polarization = 1)

ols_data <- rbind(ols_data, ols_data06, ols_data08)
glimpse(ols_data)

ols_data <- ols_data %>% 
  mutate(varb = ifelse(variables == "Unemp.",
                       se_ols^2, polarization^2*se_ols^2)) 

ols_data2 <- ols_data %>% 
  mutate(variables = ifelse(variables == "Unemp.", "Unemp.*Polarization", variables)) %>% 
  group_by(equation, polarization, variables) %>% 
  summarise(Estimate = sum(Estimate),
            vars = sum(varb),
            covb = sum(covb)) %>% 
  ungroup()
glimpse(ols_data2)

# standard error of marginal effects
ols_data2 <- ols_data2 %>% 
  mutate(se = sqrt(vars + 2*polarization*covb))
ols_data2 <- ols_data2 %>% 
  select(equation:Estimate, se)

ols_data <- ols_data %>% 
  filter(polarization == 1) %>% 
  filter(variables == "Unemp.") %>% 
  mutate(polarization = 0)
ols_data <- ols_data %>% 
  select(equation, variables, polarization, Estimate, se = se_ols)

ols_data <- rbind(ols_data, ols_data2)
glimpse(ols_data)

ols_data <- ols_data %>% 
  mutate(icii = Estimate+(1.96*se)) %>% 
  mutate(ici = Estimate-(1.96*se))

sd(model_data$unemp_rate)
mean(model_data$unemp_rate)

ols_data <- ols_data %>% 
  mutate(mean_unemp = mean(model_data$unemp_rate)) %>% 
  mutate(sd_uenmp = sd(model_data$unemp_rate)) %>% 
  mutate(estimate_mean_unemp = sd_uenmp*Estimate) %>% 
  mutate(icii_new = estimate_mean_unemp+(1.96*se)) %>% 
  mutate(ici_new = estimate_mean_unemp-(1.96*se))
glimpse(ols_data)


ols_data <- ols_data %>%
  mutate(polarization = as.factor(polarization)) %>%  
  mutate(polarization = factor(polarization, 
                               levels = c("0",
                                          "0.6",
                                          "0.85",
                                          "1"))) %>% 
  mutate(equation = "Incumbent Party")

change_ols <- ols_data %>% 
  filter(!(polarization == 1)) %>% 
  filter(!(polarization == 0)) %>% 
  #filter(variables == "Unemp.Rate" | variables == "Unemp.Rate*Polarization") %>% 
  ggplot(aes(color = polarization, shape = polarization, fill = polarization)) +
  geom_hline(yintercept = 0, colour = "gray57", lty = 2, size = .75) +
  geom_pointrange(aes(x = equation, y = estimate_mean_unemp, ymin = ici_new,
                      ymax = icii_new),
                  lwd = .65, position = position_dodge(width = .5)) + 
  theme_bw() + 
  ylab("Change in Vote Share") + xlab(NULL) + #ylim(-0.6, 0.05) +
  scale_color_manual(name = "Polarization:",
                     values = c("#009999", "#990000"), 
                     labels = c("0.60", "0.85")) +
  scale_shape_manual(name = "Polarization:",
                     values = c(24, 25), 
                     labels = c("0.60", "0.85")) +
  scale_fill_manual(name = "Polarization:",
                    values = c("#009999", "#990000"), 
                    labels = c("0.60", "0.85")) +
  #ggtitle("(c) log(Opposition/Abstention)") +
  theme(axis.text.x = element_blank(),
        axis.text.y = element_text(size = 11),
        axis.title.y = element_text(size = 13),
        legend.text = element_text(size = 13),
        legend.title = element_text(size = 14),
        legend.position = "bottom",
        legend.direction = "horizontal",
        title = element_text(size = 13)) +
  ggtitle("(b) Change in Unemployment")
change_ols


multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
  library(grid)
  # Make a list from the ... arguments and plotlist
  plots <- c(list(...), plotlist)
  numPlots = length(plots)
  # If layout is NULL, then use 'cols' to determine layout
  if (is.null(layout)) {
    # Make the panel
    # ncol: Number of columns of plots
    # nrow: Number of rows needed, calculated from # of cols
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                     ncol = cols, nrow = ceiling(numPlots/cols))
  }
  if (numPlots==1) {
    print(plots[[1]])
  } else {
    # Set up the page
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
    # Make each plot, in the correct location
    for (i in 1:numPlots) {
      # Get the i,j matrix positions of the regions that contain this subplot
      matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
      print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                      layout.pos.col = matchidx$col))
    }
  }
}
multiplot(fig_ols, change_ols, cols = 2)


